package org.edith.log.interceptor;

import com.alibaba.fastjson.JSON;
import org.edith.log.dataobject.LogDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.edith.log.service.LoggerService;
import org.edith.log.need.implement.WebLogUserService;
import org.edith.log.utils.RequestWrapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;

/**
 * 日志记录拦截器
 */
@Component("edithWebLogInterceptor")
public class LogInterceptor implements HandlerInterceptor {
    @Autowired
    @Qualifier("edithWebLogThreadPool")
    private Executor logThreadPool;

    @Autowired
    @Qualifier("edithWebLoggerService")
    private LoggerService loggerService;

    @Autowired(required = false)
    private WebLogUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(userService == null){
            throw new RuntimeException("WebLogUserServiceImpl not found!!!");
        }

        String uri = request.getRequestURI();

        RequestWrapper requestWrapper = new RequestWrapper(request);
        // 获取@RequestBody注解参数和post请求参数
        String requestBody = requestWrapper.getBody();

        // 获取get请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String,String> reqMap = new HashMap<>(16);
        if(parameterMap != null){
            parameterMap.forEach((k,v)-> reqMap.put(k,v[0]));
        }
        String getParamJson = JSON.toJSONString(reqMap);

        logThreadPool.execute(()->{
            LogDO model = new LogDO();
            model.setUri(uri);
            model.setInput(requestBody == null ||"".equals(requestBody)?getParamJson:requestBody);
            model.setOperator(JSON.toJSONString(userService.getUserInfoByRequest(request)));
            loggerService.insertLog(model);
        });
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
